package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.user.client.UserInfoFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("/api/order")
@RestController
public class OrderInfoApiController {

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private CartFeignClient cartInfoFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;


    //查询结算页面上的数据  将来提交订单
    @GetMapping("/trade")
    public Map trade(HttpServletRequest request){
        Map result = new HashMap();
        //1：收货地址
        List<UserAddress> userAddressList = userInfoFeignClient.getUserAddress();
        result.put("userAddressList",userAddressList);
        //2:购物车中选中的商品集合
        List<CartInfo> cartInfoListAndChecked = cartInfoFeignClient.findCartInfoListAndChecked();
        //商品清单
        //商品清单 ： 订单的的清单
        // 2个米、1个碑、一条鱼、一个菜 == 156元  帐单
        List<OrderDetail> orderDetailList = cartInfoListAndChecked.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            return orderDetail;
        }).collect(Collectors.toList());

        result.put("detailArrayList",orderDetailList);
        //3:总计      规约
        //总件数
        long totalNum = orderDetailList.stream().collect(Collectors.summarizingInt(orderDetail -> {
            return orderDetail.getSkuNum();
        })).getSum();
        result.put("totalNum",totalNum);
        //总金额
        //传统或原来的写法
  /*      BigDecimal totalPrice = new BigDecimal(0);
        for (OrderDetail orderDetail : orderDetailList) {
            totalPrice = totalPrice.add(orderDetail.getOrderPrice()
                    .multiply(new BigDecimal(orderDetail.getSkuNum())));
        }*/
        //Stream流式写法
        BigDecimal totalAmount = orderDetailList.stream().map(orderDetail ->
                orderDetail.getOrderPrice()
                        .multiply(new BigDecimal(orderDetail.getSkuNum()))
        ).reduce(BigDecimal.ZERO, BigDecimal::add);

        System.out.println("totalAmount:" + totalAmount);
        result.put("totalAmount",totalAmount);
        //4：订单号 交易号
        String uuid = UUID.randomUUID().toString();
        String userId = AuthContextHolder.getUserId(request);
        redisTemplate.opsForValue().set("tradeNo:" + userId ,uuid);
        result.put("tradeNo",uuid);
        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, String tradeNo, HttpServletRequest request) {
        //1:校验交易号 防止二次提交订单（幂等性）
        String userId = AuthContextHolder.getUserId(request);
        if (!StringUtils.isEmpty(tradeNo)) {
            String value = (String) redisTemplate.opsForValue().get("tradeNo:" + userId);
            if (StringUtils.isEmpty(value)) {
                return Result.fail().message("请不要重复提交订单");
            } else {
                //比较
                if (tradeNo.equals(value)) {
                    //删除
                    redisTemplate.delete("tradeNo:" + userId);
                } else {
                    return Result.fail().message("请求不合法");
                }
            }
        } else {
            return Result.fail().message("请求不合法");
        }
        //2:校验商品是否还有库存？ 库存定义： 购买数量大于剩余库存数量 视为库存不足
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            Boolean isHave = orderInfoService.hasStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
            if (!isHave) {
                //表示无货
                return Result.fail().message(orderDetail.getSkuName() + ":[库存不足]");
            }
        }
        ;
        //保存订单的
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.saveOrderInfo(orderInfo);


        return Result.ok(orderId);
    }

    //根据订单Id 查询一个订单对象
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
         return orderInfoService.getOrderInfo(orderId);
    }

    //开始拆单
    @PostMapping("/orderSplit")
    public List<Map> orderSplit(Long orderId , String wareSkuMap){//本次安例是1张订单拆分成2张订单
        //   [{"wareId":"2","skuIds":["1","8"]},{"wareId":"1","skuIds":["2","5"]}]
        //一张原订单拆分之后 变成多张子订单
        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
        //返回值
        return orderInfoList.stream().map(orderInfo -> {
            return orderInfoService.initWareData(orderInfo);
        }).collect(Collectors.toList());

    }
}
